<?php
//touch("lock");
require_once("../shared/connect.php");

$timestamp = time();

define('LOCK_TIMEOUT', 30);

// delete all locks older than LOCK_TIMEOUT seconds
function clear_old_locks() {
	$sql = "DELETE FROM `lock` WHERE last_modified < ".(time() - LOCK_TIMEOUT);
	mysql_query($sql) or die(mysql_error());
}

if ($_GET['name'] == "lock_van" && $_GET['van'] != "") {

	clear_old_locks();

	$sql = "SELECT * FROM `lock` WHERE van = $_GET[van]";
	$query = mysql_query($sql) or die(mysql_error());

	if ($row = mysql_fetch_assoc($query)) { // van already locked?
		die("Warning: Trying to lock when already locked.");
	}

	// add van lock
	$sql = "INSERT INTO `lock` (name, van, count, last_modified) VALUES ('$_GET[name]', '$_GET[van]', 1, '$timestamp')";
	$query = mysql_query($sql) or die(mysql_error());
	echo mysql_insert_id();

} else if ($_GET['name'] == "lock_refresh") { // refresh_lock

	clear_old_locks();
	/*
	$sql = "SELECT * FROM `lock` WHERE name = 'lock_refresh'";
	$query = mysql_query($sql) or die(mysql_error());

	if ($row = mysql_fetch_assoc($query)) { // lock_refresh already present; increment it
		$sql = "UPDATE `lock` SET count = count + 1 WHERE name = 'lock_refresh'";
	} else { // need to add lock_refresh
		$sql = "INSERT INTO `lock` (name, van, count) VALUES ('$_GET[name]', NULL, 1)";
	}*/
	$sql = "INSERT INTO `lock` (name, van, count, last_modified) VALUES ('$_GET[name]', NULL, 1, '$timestamp')";

	$query = mysql_query($sql) or die(mysql_error());
	echo mysql_insert_id();

} else {
	die("Bad parameters? (lock)");
}
?>